//
//  MAPhotoListViewController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/30.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAPhotoListViewController.h"
#import "MAJiGouModel.h"
#import "MAStaffCell.h"
#import "MAPhotoListModel.h"
#import "MAMgrPopView.h"
#import <zhPopupController.h>
#import "MABabyRelationshipView.h"
#import "WGQFamilyAlbumViewController.h"


@interface MAPhotoListViewController ()
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

/** photoListModels */
@property(nonatomic,strong) NSMutableArray *photoListModels;

/** alertView */
@property(nonatomic,strong) MABabyRelationshipView *alertView;

/** renameModel */
@property(nonatomic,strong) MAPhotoListModel *renameModel;
@end

@implementation MAPhotoListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBasic];
    
    [self setupTableView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenTabbar:YES];
}
- (void)setupBasic {
    self.title = @"相册列表";
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightItemDidClick) image:@"Exclamation point" highImage:@"Exclamation point"];
    
}

- (void)setupTableView {
    
    self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.myTableView.tableFooterView = [UIView new];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestMsgData)];
    [self.myTableView.mj_header beginRefreshing];
    
    //    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(<#method#>)];
    //    self.myTableView.mj_footer.hidden = YES;
}

- (void)rightItemDidClick {
    DLog(@"");
}

- (void)requestMsgData {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=family_album&status=1",BASE_LISTENTITY_LIST,self.jigouModel.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.photoListModels = [MAPhotoListModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            
            [self.myTableView reloadData];
            [self.myTableView.mj_header endRefreshing];
            self.myTableView.mj_footer.hidden = NO;
            [self.myTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
            
            [self.myTableView.mj_header endRefreshing];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
        [self.myTableView.mj_header endRefreshing];
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.photoListModels.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    MAPhotoListModel *listModel = self.photoListModels[row];
    return listModel.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    
    MAPhotoListModel *listModel = self.photoListModels[row];
    MAStaffCell *cell = [MAStaffCell cellWithTableView:tableView];
    cell.photoListModel = listModel;
    
    UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongPress:)];
    
    longPressGesture.minimumPressDuration = 1.0f;//设置长按 时间
    [cell addGestureRecognizer:longPressGesture];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DLog(@"");
    WGQFamilyAlbumViewController * vc = [[WGQFamilyAlbumViewController alloc] init];
    MAPhotoListModel *listModel = self.photoListModels[indexPath.row];
    vc.photo_id = listModel.ID;
    [self.navigationController pushViewController:vc animated:YES];

}

- (void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer {
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        
        CGPoint location = [longRecognizer locationInView:self.myTableView];
        NSIndexPath * indexPath = [self.myTableView indexPathForRowAtPoint:location];
        //可以得到此时你点击的哪一行
        
        //在此添加你想要完成的功能
        DLog(@"");
        NSMutableArray *titleArr = [NSMutableArray array];
        titleArr = [@[@"添加相册", @"删除当前相册", @"重命名当前相册"] mutableCopy];
        
        MAMgrPopView *popView = [MAMgrPopView popViewWithTitles:titleArr clickBlock:^(NSInteger clickIdx) {
            DLog(@"============%ld",clickIdx);
            [self.zh_popupController dismiss];
            if (clickIdx == 0) { // 添加
                MABabyRelationshipView *alertView = [MABabyRelationshipView babyRelationshipView];
                alertView.layer.cornerRadius = 10;
                alertView.layer.masksToBounds = YES;
                self.zh_popupController = [[zhPopupController alloc] init];
                self.zh_popupController.dismissOnMaskTouched = YES;
                self.zh_popupController.dismissOppositeDirection = YES;
                self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
                [self.zh_popupController presentContentView:alertView duration:0.35 springAnimated:YES];
                alertView.titleLabel.text = @"新建相册";
                
                [alertView okBtnAddTarget:self action:@selector(addPhoto)];
                [alertView cancelBtnAddTarget:self action:@selector(cancel)];
                self.alertView = alertView;
            } else if (clickIdx == 1) { // 删除
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要取消关注?" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    [self requestDeletePhotoWithModel:self.photoListModels[indexPath.row]];
                }];
                [alert addAction:cancel];
                [alert addAction:ok];
                [self.navigationController presentViewController:alert animated:YES completion:nil];
            } else { // 重命名
                self.renameModel = self.photoListModels[indexPath.row];
                MABabyRelationshipView *alertView = [MABabyRelationshipView babyRelationshipView];
                alertView.layer.cornerRadius = 10;
                alertView.layer.masksToBounds = YES;
                self.zh_popupController = [[zhPopupController alloc] init];
                self.zh_popupController.dismissOnMaskTouched = YES;
                self.zh_popupController.dismissOppositeDirection = YES;
                self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
                [self.zh_popupController presentContentView:alertView duration:0.35 springAnimated:YES];
                alertView.titleLabel.text = @"重命名相册";
                [alertView okBtnAddTarget:self action:@selector(renamePhoto)];
                [alertView cancelBtnAddTarget:self action:@selector(cancel)];
                self.alertView = alertView;
            }
        }];
        popView.layer.cornerRadius = 10;
        popView.layer.masksToBounds = YES;
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
    }
}

- (void)requestDeletePhotoWithModel:(MAPhotoListModel *)model {
    DLog(@"");
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    //    "entity_type": "user_notice",
    //    "entity_id": "机构ID",
    //    "org_id": "机构ID"
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",ALBUM_DELETE,model.ID] parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                [self requestMsgData];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

- (void)addPhoto {
    DLog(@"%@",self.alertView.nameTF.text);
    if (!self.alertView.nameTF.text.length) {
        [MBManager showBriefAlert:@"请填写相册名称"];
        return;
    }
    [self requestAddPhoto];
}
- (void)renamePhoto {
    DLog(@"%@",self.alertView.nameTF.text);
    if (!self.alertView.nameTF.text.length) {
        [MBManager showBriefAlert:@"请填写相册名称"];
        return;
    }
    [self requestRenamePhotoWithModel:self.renameModel];
}

- (void)cancel {
    DLog(@"");
    [self.zh_popupController dismiss];
}
- (void)requestAddPhoto {
    DLog(@"");
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    body[@"type"] = @"family";
    body[@"entityid"] = self.jigouModel.ID;
    body[@"ccaption"] = self.alertView.nameTF.text;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",ALBUM_ADD,self.jigouModel.ID] parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                [self.zh_popupController dismiss];
                [self requestMsgData];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}
- (void)requestRenamePhotoWithModel:(MAPhotoListModel *)model {
    DLog(@"");
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    body[@"id"] = model.ID;
    body[@"ccaption"] = self.alertView.nameTF.text;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@",ALBUM_UPDATE] parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                [self.zh_popupController dismiss];
                [self requestMsgData];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

- (NSMutableArray *)photoListModels {
    if (_photoListModels == nil) {
        _photoListModels = [NSMutableArray array];
    }
    return _photoListModels;
}

@end
